package jp.seraph.jsmf.motion;

import java.util.HashMap;
import java.util.Map;

import jp.seraph.jsade.core.Player;
import jp.seraph.jsade.core.World;
import jp.seraph.jsade.task.AbstractTask;
import jp.seraph.jsade.util.Executor;
import jp.seraph.jspf.pose.DefaultPose;
import jp.seraph.jspf.pose.Pose;

public class SessionTask extends AbstractTask {
    public SessionTask(MotionSession aSession){
        mElementTaskMap = new HashMap<String, ElementTask>();
        mBasePose = null;
        mFinishedCount = 0;

        mFinishedListener = new Executor(){
            public void execute(){
                mFinishedCount++;
                if(mFinishedCount == mElementTaskMap.size())
                    complete();
            }
        };

        for (MotionElement tElement : aSession.toElementList()) {
            ElementTask tTask = tElement.toTask(this);
            tTask.addCanceledListener(mFinishedListener);
            tTask.addCompletedListener(mFinishedListener);

            mElementTaskMap.put(tElement.getName(), tTask);
        }
    }

    private Pose mBasePose;
    private Executor mFinishedListener;
    private Map<String, ElementTask> mElementTaskMap;
    private int mFinishedCount;

    @Override
    public void execute(World aWorld, Player aPlayer) {
        if(mBasePose == null)
            mBasePose = new DefaultPose(aWorld.getModelManager());

        for (ElementTask tElementTask : mElementTaskMap.values()) {
            if(tElementTask.canExecute()){
                if(!tElementTask.isRunning())
                    tElementTask.init();

                tElementTask.execute(aWorld, aPlayer);
            }
        }
    }

    /**
     *
     * @see jp.seraph.jsade.task.AbstractTask#init()
     */
    @Override
    public void init() {
        mBasePose = null;
        super.init();
    }

    public ElementTask getElementTask(String aElementName){
        return mElementTaskMap.get(aElementName);
    }
}
